import base from "@/base"
import store from '@/store/index.js'

export const GET = "GET"
export const POST = "POST"
export const PUT = "PUT"
export const PATCH = "PATCH"
export const DELETE = "DELETE"

/*
需要特别处理某个错误的时候:
	let param = {}
	try {
		await this.$u.$api.leave_add(param, { _customError: true })
	} catch(e) {
		console.log(e)
		let msg = (e.data && e.data[0]) || e.msg || "出错了"
		uni.showModal({ title: "错误", content: msg, showCancel: false, confirmColor: "#00cca0" })
	}
*/
export function request(method, url, data, config = {}) {
	const {
		token
	} = store.getters
	return new Promise((resolve, reject) => {
		let header = {
			"content-type": "application/json",
			token,
			...config
		}
		uni.request({
			url: base.baseUrl + url,
			data: method === "POST" ? JSON.stringify(data) : data,
			method,
			header,
			success: (resp) => {
				if (resp.statusCode == 200) {
					//成功
					if (resp.data.code == 1) {
						resolve(resp.data.data)
					} else {
						if (!config || !config._customError) {
							let msg = resp.data.msg ? resp.data.msg : "未知错误"
							uni.showToast({
								title: msg,
								icon: 'none',
								duration: 2000
							})
						}
						console.log(url, resp.data);
						reject(resp.data)
					}
				} else if (resp.statusCode == 401) {
					store.dispatch('clear_loginInfo') //清理登录信息
					store.dispatch('do_login')
					reject(resp.data)
					uni.showToast({
						title: resp.data.msg,
						icon: "none",
						duration: 2000
					})
				} else if (resp.statusCode == 502) {
					uni.showToast({
						title: "服务器正在部署",
						icon: "none",
						duration: 2000
					})
					reject(resp)
				} else if (resp.statusCode == 500) {
					reject(resp)
					uni.showToast({
						title: "接口报错了",
						icon: "none",
						duration: 2000
					})
				} else {
					reject(resp)
					uni.showToast({
						title: "网络开小差了",
						icon: "none",
						duration: 2000
					})
				}

			},
			fail: (err) => {
				uni.hideLoading()
				reject(err)
				uni.showToast({
					title: '您的网络开小差了，数据加载失败',
					icon: 'none',
					duration: 2000
				})
			},
		})
	})
}